package com.hotelManager.www.servlet;

import com.google.gson.JsonObject;
import com.hotelManager.www.controller.CustomerController;
import com.hotelManager.www.po.*;
import com.hotelManager.www.common.Result;
import com.hotelManager.www.common.ResultCode;
import com.hotelManager.www.service.RoomService;
import com.hotelManager.www.service.ShopService;
import com.hotelManager.www.service.OrderService;
import com.hotelManager.www.service.RoomTypeService;
import com.hotelManager.www.config.GsonConfig;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import com.google.gson.Gson;


/**
 * 客户端Servlet
 * 处理客户端用户相关的HTTP请求，包括个人信息管理、充值、浏览店铺、订房等功能
 * 使用@WebServlet注解映射URL路径"/customer/*"
 */
@WebServlet("/customer/*")
public class CustomerServlet extends HttpServlet {
    // 创建ClientController实例，用于处理业务逻辑
    private final CustomerController clientController = new CustomerController();
    // 创建Gson实例，用于JSON序列化和反序列化
    private final Gson gson = GsonConfig.getGson();
    private final ShopService shopService = new ShopService();
    private final RoomTypeService roomTypeService = new RoomTypeService();
    private final OrderService orderService = new OrderService();

    /**
     * 处理POST请求
     * 主要处理需要提交数据的操作，如修改个人信息、充值、订房、退订、收藏店铺等
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @throws IOException IO异常
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取当前登录的客户用户
        HttpSession session = req.getSession();
        User customerUser = (User) session.getAttribute("user");
        
        // 获取请求路径
        String pathInfo = req.getPathInfo();
        
        switch (pathInfo) {

            case "/recharge":
                // 处理充值请求
                handleRecharge(req, resp, customerUser);
                break;
            case "/book":
                // 处理订房请求
                handleBookRoom(req, resp, customerUser);
                break;
            case "/favorite":
                // 处理收藏店铺请求
                handleFavoriteShop(req, resp, customerUser);
                break;
            case "/unfavorite":
                // 处理取消收藏店铺请求
                handleUnfavoriteShop(req, resp, customerUser);
                break;
            case "/signin":
                // 处理每日签到请求
                handleDailySignIn(req, resp, customerUser);
                break;
            case "/blacklist":
                // 处理拉黑商家请求
                handleBlacklistShop(req, resp, customerUser);
                break;
            case "/browse/record":
                // 处理记录浏览历史请求
                handleRecordBrowseHistory(req, resp, customerUser);
                break;
            case "/pay":
                // 处理支付请求
                handlePayOrder(req, resp, customerUser);
                break;
          
            default:
                // 未知操作，返回错误信息
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "未知操作")));
        }
    }

    /**
     * 处理GET请求
     * 主要处理查询操作，如查看余额、浏览店铺、搜索店铺查看历史订单等
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @throws ServletException Servlet异常
     * @throws IOException IO异常
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getPathInfo();
        System.out.println("[CustomerServlet] 收到GET请求: " + path);
        
        // 获取当前登录的客户用户
        HttpSession session = req.getSession();
        User customerUser = (User) session.getAttribute("user");
        
        // 获取请求路径
        String pathInfo = req.getPathInfo();
        System.out.println("请求路径: " + pathInfo); // 调试日志
        
        // 先处理特殊路径，修复路径匹配问题
        if (pathInfo == null) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "路径不能为空")));
            return;
        }
        
        // 确保特殊路径先检查，避免被默认case捕获
        if (pathInfo.equals("/shops/roomtypes")) {
            handleShopRoomTypes(req, resp);
            return;
        }
        
        switch (pathInfo) {
            case "/balance":
                // 处理查看余额请求
                handleViewBalance(req, resp, customerUser);
                break;
            case "/shops":
                // 处理浏览店铺请求
                handleBrowseShops(req, resp);
                break;
            case "/shops/search":
                // 处理搜索店铺请求
                handleSearchShops(req, resp);
                break;
            case "/shops/sort":
                // 处理按销量排序店铺请求
                handlegetShopsBySalesVolume(req, resp);
                break;
            case "/shops/favorite":
                // 处理查看收藏店铺请求
                handleViewFavoriteShops(req, resp, customerUser);
                break;
            case "/orders":
                // 处理查看历史订单请求
                handleviewHistoryOrders(req, resp, customerUser);
                break;
            case "/browse/history":
                // 处理查看浏览历史请求
                handleViewBrowseHistory(req, resp, customerUser);
                break;
            case "/shops/detail":
                handleShopDetail(req, resp);
                break;
            case "/rooms":
                // 处理查看可用房间请求
                handleViewAvailableRooms(req, resp);
                System.out.println("pathInfo: " + pathInfo);
                break;

                case "/signin/stats":
                // 处理获取签到统计数据请求
                handleSignInStats(req, resp, customerUser);
                break;
            case "/signin/history":
                // 处理获取签到历史记录请求
                handleSignInHistory(req, resp, customerUser);
                break;
            default:
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.NOT_FOUND, "未知操作：" + path)));
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String path = req.getPathInfo();
        System.out.println("[CustomerServlet.doPut] 收到PUT请求: " + path);

        // 获取当前登录的客户用户
        HttpSession session = req.getSession();
        User customerUser = (User) session.getAttribute("user");
        System.out.println("[CustomerServlet.doPut] 当前用户信息: " + (customerUser != null ? "ID=" + customerUser.getId() : "未登录"));

        // 获取请求路径
        String pathInfo = req.getPathInfo();
        System.out.println("[CustomerServlet.doPut] 请求路径: " + pathInfo);

        // 先处理特殊路径，修复路径匹配问题
        if (pathInfo == null || pathInfo.trim().isEmpty()) {
            System.out.println("[CustomerServlet.doPut] 路径为空");
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "请求路径不能为空")));
            return;
        }

        switch (pathInfo) {
            case "/update":
                // 处理修改个人信息请求
                System.out.println("[CustomerServlet.doPut] 进入修改个人信息处理分支");
                handleUpdateUserInfo(req, resp, customerUser);
                break;
            case "/cancel":
                // 处理退订请求
                handleCancelOrder(req, resp, customerUser);
                break;
            case "/refund":
                // 处理退房申请请求
                handleRefundRequest(req, resp, customerUser);
                break;
            default:
                // 未知路径
                System.out.println("[CustomerServlet.doPut] 未知路径: " + pathInfo);
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.NOT_FOUND, "未知操作：" + pathInfo)));
        }
    }

    /**
     * 处理修改个人信息请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleUpdateUserInfo(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        System.out.println("[CustomerServlet.handleUpdateUserInfo] 开始处理用户信息更新");
        
        if (customerUser == null) {
            System.out.println("[CustomerServlet.handleUpdateUserInfo] 错误：用户未登录");
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.UNAUTHORIZED, "用户未登录")));
            return;
        }

        // 获取修改参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("[CustomerServlet.handleUpdateUserInfo] 接收到的参数 - username: " + username + ", password: " + password);
        
        // 创建用户对象并设置修改的信息
        User user = new User();
        user.setId(customerUser.getId());
        user.setUsername(username != null ? username : customerUser.getUsername());
        user.setPassword(password != null ? password : customerUser.getPassword());
        user.setRole(customerUser.getRole());
        
        System.out.println("[CustomerServlet.handleUpdateUserInfo] 准备更新的用户信息 - ID: " + user.getId() 
            + ", 新用户名: " + user.getUsername() 
            + ", 新密码: " + (user.getPassword() != null ? "已设置" : "未设置")
            + ", 角色: " + user.getRole());
        
        // 调用控制器进行修改
        boolean success = clientController.updateUserInfo(user);
        System.out.println("[CustomerServlet.handleUpdateUserInfo] 更新结果: " + (success ? "成功" : "失败"));
        
        // 返回修改结果
        if (success) {
            // 更新session中的用户信息
            req.getSession().setAttribute("user", user);
            System.out.println("[CustomerServlet.handleUpdateUserInfo] session中的用户信息已更新");
            resp.getWriter().write(gson.toJson(Result.success("修改成功")));
        } else {
            System.out.println("[CustomerServlet.handleUpdateUserInfo] 修改失败");
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "修改失败")));
        }
    }

    /**
     * 处理充值请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleRecharge(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        // 获取充值金额
        String amountStr = req.getParameter("amount");
        if (amountStr == null || amountStr.trim().isEmpty()) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "充值金额不能为空")));
            return;
        }
        
        try {
            int amount = Integer.parseInt(amountStr);
            if (amount <= 0) {
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "充值金额必须大于0")));
                return;
            }
            
            // 调用控制器进行充值
            boolean success = clientController.recharge(customerUser, amount);
            
            // 返回充值结果
            if (success) {
                resp.getWriter().write(gson.toJson(Result.success("充值申请已提交，请等待管理员审核")));
            } else {
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "充值失败")));
            }
        } catch (NumberFormatException e) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "充值金额格式不正确")));
        }
    }

    /**
     * 处理订房请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleBookRoom(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        // 获取订房参数
        BufferedReader reader = req.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        JsonObject jsonObject = gson.fromJson(jsonBuilder.toString(), JsonObject.class);

        String shopIdStr = jsonObject.get("shopId").getAsString();
        String roomIdStr = jsonObject.get("roomId").getAsString();
        String daysStr = jsonObject.get("days").getAsString();
        if (shopIdStr == null || roomIdStr == null || daysStr == null ||
            shopIdStr.trim().isEmpty() || roomIdStr.trim().isEmpty() || daysStr.trim().isEmpty()) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "订房参数不完整")));
            return;
        }
        
        try {
            int shopId = Integer.parseInt(shopIdStr);
            int days = Integer.parseInt(daysStr);
            int roomId = Integer.parseInt(roomIdStr);

            
            if (days <= 0) {
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "入住天数必须大于0")));
                return;
            }
            // 调用控制器进行订房，捕获所有异常并反馈详细信息
            try {
                CustomerController customerController = new CustomerController();
                Order order = customerController.bookRoom(customerUser.getId(), shopId,roomId, days);
                if (order != null) {
                    resp.getWriter().write(gson.toJson(Result.success(order, "订单生成成功")));
                } else {
                    // 理论上不应走到这里，所有失败都应抛出异常
                    resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "生成失败，未知原因")));
                }
            } catch (Exception e) {
                // 记录详细日志，反馈异常信息到前端
                e.printStackTrace();
                System.err.println("订房失败，参数：shopId=" + shopId + ", roomId=" + roomId + ", days=" + days + ", userId=" + customerUser.getId());
                System.err.println("异常信息：" + e.getMessage());
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "订房失败：" + e.getMessage())));
            }
        } catch (NumberFormatException e) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "参数格式不正确")));
        }
    }

    /**
     * 处理退订请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleCancelOrder(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        // 获取订单ID
        BufferedReader reader = req.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        JsonObject jsonObject = gson.fromJson(jsonBuilder.toString(), JsonObject.class);
        String orderIdStr = jsonObject != null && jsonObject.has("orderId") ? jsonObject.get("orderId").getAsString() : null;
        if (orderIdStr == null || orderIdStr.trim().isEmpty()) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "订单ID不能为空")));
            return;
        }
        
        try {
            Integer orderId = Integer.parseInt(orderIdStr);
            
            // 调用控制器进行退订
            boolean success = clientController.cancelOrder(customerUser.getId(), orderId);
            
            // 返回退订结果
            if (success) {
                resp.getWriter().write(gson.toJson(Result.success("退订申请已提交，请等待商家审核")));
            } else {
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "退订失败")));
            }
        } catch (NumberFormatException e) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "订单ID格式不正确")));
        }
    }

    /**
     * 处理收藏店铺请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleFavoriteShop(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        // 从请求体中读取JSON数据
        BufferedReader reader = req.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        JsonObject jsonObject = gson.fromJson(jsonBuilder.toString(), JsonObject.class);
        String shopIdStr = jsonObject != null && jsonObject.has("shopId") ? jsonObject.get("shopId").getAsString() : null;

        if (shopIdStr == null || shopIdStr.trim().isEmpty()) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID不能为空")));
            return;
        }
        
        try {
            Integer shopId = Integer.parseInt(shopIdStr);
            
            // 调用控制器进行收藏
            boolean success = clientController.favoriteShop(customerUser.getId(), shopId);
            
            // 返回收藏结果
            if (success) {
                resp.getWriter().write(gson.toJson(Result.success("收藏成功")));
            } else {
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "收藏失败")));
            }
        } catch (NumberFormatException e) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID格式不正确")));
        }
    }

    /**
     * 处理取消收藏店铺请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleUnfavoriteShop(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        // 获取店铺ID
        String shopIdStr = req.getParameter("shopId");
        if (shopIdStr == null || shopIdStr.trim().isEmpty()) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID不能为空")));
            return;
        }
        
        try {
            Integer shopId = Integer.parseInt(shopIdStr);
            
            // 调用控制器进行取消收藏
            boolean success = clientController.unfavoriteShop(customerUser.getId(), shopId);
            
            // 返回取消收藏结果
            if (success) {
                resp.getWriter().write(gson.toJson(Result.success("取消收藏成功")));
            } else {
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "取消收藏失败")));
            }
        } catch (NumberFormatException e) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID格式不正确")));
        }
    }

    /**
     * 处理每日签到请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
     private void handleDailySignIn(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        System.out.println("[handleDailySignIn] 开始处理每日签到请求");
        if (customerUser == null) {
            System.out.println("[handleDailySignIn] 用户未登录");
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.UNAUTHORIZED, "用户未登录")));
            return;
        }
        System.out.println("[handleDailySignIn] 用户ID: " + customerUser.getId());

        // 调用控制器进行签到
        boolean success = clientController.dailySignIn(customerUser.getId());
        System.out.println("[handleDailySignIn] 签到结果: " + (success ? "成功" : "失败"));

        // 返回签到结果
        if (success) {
            resp.getWriter().write(gson.toJson(Result.success("签到成功")));
        } else {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "签到失败")));
        }
    }

    /**
     * 处理拉黑商家请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleBlacklistShop(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        // 从请求体中读取JSON数据
        BufferedReader reader = req.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        JsonObject jsonObject = gson.fromJson(jsonBuilder.toString(), JsonObject.class);
        String shopIdStr = jsonObject != null && jsonObject.has("shopId") ? jsonObject.get("shopId").getAsString() : null;
        if (shopIdStr == null || shopIdStr.trim().isEmpty()) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID不能为空")));
            return;
        }
        
        try {
            Integer shopId = Integer.parseInt(shopIdStr);
            
            // 调用控制器进行拉黑
            boolean success = clientController.blacklistShop(customerUser.getId(), shopId);
            
            // 返回拉黑结果
            if (success) {
                System.out.println("[handleBlacklistShop] 拉黑商家成功，用户ID: " + customerUser.getId() + ", 店铺ID: " + shopId);
                resp.getWriter().write(gson.toJson(Result.success("拉黑成功")));
            } else {
                System.err.println("[handleBlacklistShop] 拉黑商家失败，用户ID: " + customerUser.getId() + ", 店铺ID: " + shopId);
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "拉黑失败")));
            }
        } catch (NumberFormatException e) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID格式不正确")));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理查看余额请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleViewBalance(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        try {
            // 调用控制器查看余额
            User user = clientController.viewBalance(customerUser.getId());

            if (user != null) {
                // 构造返回数据
                Map<String, Object> data = new HashMap<>();
                data.put("balance", user.getBalance());
                data.put("status", "active");
                data.put("userId", user.getId());
                data.put("username", user.getUsername());
                System.out.println("查到的用户余额为: " + user.getBalance());

                resp.getWriter().write(gson.toJson(Result.success(data, "获取余额成功")));
            } else {
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "获取余额失败")));
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "获取余额失败：" + e.getMessage())));
        }
    }
    /**
     * 处理浏览店铺请求
     * 支持分页查询
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @throws IOException IO异常
     */
    private void handleBrowseShops(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取分页参数
        String pageStr = req.getParameter("page");
        String pageSizeStr = req.getParameter("pageSize");
        String keyword = req.getParameter("keyword");
        String sortField = req.getParameter("sortField");
        String sortOrder = req.getParameter("sortOrder");
        if (keyword == null) keyword = "";
        if (sortField == null) sortField = "sales_volume";
        if (sortOrder == null) sortOrder = "desc";
        int page = 1;
        int pageSize = 10;
        if (pageStr != null && !pageStr.trim().isEmpty()) {
            try { page = Integer.parseInt(pageStr); } catch (NumberFormatException e) { }
        }
        if (pageSizeStr != null && !pageSizeStr.trim().isEmpty()) {
            try { pageSize = Integer.parseInt(pageSizeStr); } catch (NumberFormatException e) { }
        }
        // 调用控制器获取分页数据
        Map<String, Object> result = clientController.browseShops(keyword, page, pageSize, sortField, sortOrder);
        resp.getWriter().write(gson.toJson(Result.success(result)));
    }
    /**
     * 处理搜索店铺请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @throws IOException IO异常
     */
    private void handleSearchShops(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取搜索关键词
        String keyword = req.getParameter("keyword");
        if (keyword == null || keyword.trim().isEmpty()) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "搜索关键词不能为空")));
            return;
        }
        
        // 调用控制器搜索店铺
        // Provide default values for page and pageSize
        int page = 1;
        int pageSize = 10;
        List<Shop> shops = clientController.searchShops(keyword, page, pageSize);
        
        // 返回搜索结果
        resp.getWriter().write(gson.toJson(Result.success(shops)));
    }

    /**
     * 处理按销量排序店铺请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @throws IOException IO异常
     */
    private void handlegetShopsBySalesVolume(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 调用控制器按销量排序店铺
        List<Shop> shops = clientController.getShopsBySalesVolume();
        
        // 返回排序结果
        resp.getWriter().write(gson.toJson(Result.success(shops)));
    }

    /**
     * 处理查看收藏店铺请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleViewFavoriteShops(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        // 调用控制器获取收藏店铺
        List<Shop> shops = clientController.viewFavoriteShops(customerUser.getId());
        System.out.println("[handleViewFavoriteShops] 返回的收藏店铺列表: " + gson.toJson(shops));
        resp.getWriter().write(gson.toJson(Result.success(shops)));
    }

    /**
     * 处理查看历史订单请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */

    private void handleviewHistoryOrders(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        // 调用控制器获取历史订单
        List<Order> orders = clientController.viewHistoryOrders(customerUser.getId());

        // 打印获取的历史订单列表到控制台，确保数据正确
        System.out.println("[handleviewHistoryOrders] 获取的历史订单: " + gson.toJson(orders));

        // 返回历史订单列表
        resp.getWriter().write(gson.toJson(Result.success(orders)));
    }

    /**
     * 处理查看浏览历史请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleViewBrowseHistory(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        // 调用控制器获取浏览历史
        List<BrowseHistory> histories = clientController.viewBrowseHistory(customerUser.getId());
        
        // 返回浏览历史列表
        resp.getWriter().write(gson.toJson(Result.success(histories)));
    }

    /**
     * 处理记录浏览历史请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleRecordBrowseHistory(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        // 获取店铺ID
        String shopIdStr = req.getParameter("shopId");
        if (shopIdStr == null || shopIdStr.trim().isEmpty()) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID不能为空")));
            return;
        }
        
        try {
            Integer shopId = Integer.parseInt(shopIdStr);
            
            // 调用控制器记录浏览历史
            boolean success = clientController.recordBrowseHistory(customerUser.getId(), shopId);
            
            // 返回记录结果
            if (success) {
                resp.getWriter().write(gson.toJson(Result.success("记录浏览历史成功")));
            } else {
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "记录浏览历史失败")));
            }
        } catch (NumberFormatException e) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID格式不正确")));
        }
    }

    /**
     * 处理店铺详情请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @throws IOException IO异常
     */
    private void handleShopDetail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String shopIdStr = req.getParameter("shopId");
        if (shopIdStr == null || shopIdStr.trim().isEmpty()) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID不能为空")));
            return;
        }

        try {
            int shopId = Integer.parseInt(shopIdStr);
            // 使用clientController.getShopDetail方法，其内部会调用shopService.getShopBriefById方法
            Shop shop = clientController.getShopDetail(shopId);
            if (shop == null) {
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.NOT_FOUND, "店铺不存在")));
                return;
            }

            List<RoomType> roomTypes = roomTypeService.getRoomTypesByShopId(shopId);

            Map<String, Object> data = new HashMap<>();
            data.put("shop", shop);  // 此时shop对象包含了地址和联系方式等信息
            data.put("roomTypes", roomTypes);

            resp.getWriter().write(gson.toJson(Result.success(data, "获取店铺详情成功")));
        } catch (NumberFormatException e) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID格式不正确")));
        }
    }

    /**
     * 处理获取店铺房型请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @throws IOException IO异常
     */
    private void handleShopRoomTypes(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String shopIdStr = req.getParameter("shopId");
        System.out.println("[CustomerServlet] 请求房型列表, shopId=" + shopIdStr);
        
        try {
            if (shopIdStr == null || shopIdStr.trim().isEmpty()) {
                System.out.println("[CustomerServlet] shopId为空");
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID不能为空")));
                return;
            }

            int shopId = Integer.parseInt(shopIdStr);
            System.out.println("[CustomerServlet] 解析shopId=" + shopId);
            
            // 先检查店铺是否存在
            Shop shop = shopService.findById(shopId);
            System.out.println("[CustomerServlet] 查询店铺结果: " + shop);
            
            if (shop == null) {
                System.out.println("[CustomerServlet] 店铺不存在");
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.NOT_FOUND, "店铺不存在")));
                return;
            }
            
            // 获取房型列表
            List<RoomType> roomTypes = roomTypeService.getRoomTypesByShopId(shopId);
            System.out.println("[CustomerServlet] 查询到房型数量: " + (roomTypes == null ? "null" : roomTypes.size()));
            
            if (roomTypes == null) {
                System.out.println("[CustomerServlet] 房型列表为null");
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "获取房型列表失败")));
                return;
            }
            
            if (roomTypes.isEmpty()) {
                System.out.println("[CustomerServlet] 房型列表为空");
                resp.getWriter().write(gson.toJson(Result.success(new ArrayList<>(), "该店铺暂无房型")));
                return;
            }
            
            System.out.println("[CustomerServlet] 成功获取到" + roomTypes.size() + "个房型");
            resp.getWriter().write(gson.toJson(Result.success(roomTypes, "获取房型列表成功")));
            
        } catch (NumberFormatException e) {
            System.out.println("[CustomerServlet] shopId格式错误: " + e.getMessage());
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺ID格式不正确")));
        } catch (Exception e) {
            System.out.println("[CustomerServlet] 获取房型数据出错: " + e.getMessage());
            e.printStackTrace();
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "获取房型列表失败：" + e.getMessage())));
        }
    }

    /**
     * 处理查看可用房间请求
     * 支持通过shopId或roomTypeId查询
     */    /**
     * 处理查看可用房间请求
     * 支持通过shopId或roomTypeId查询
     */
    private void handleViewAvailableRooms(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 设置响应内容类型
        resp.setContentType("application/json;charset=UTF-8");

        String shopIdStr = req.getParameter("shopId");
        String roomTypeIdStr = req.getParameter("roomTypeId");

        System.out.println("接收到查询可用房间请求，参数: shopId=" + shopIdStr + ", roomTypeId=" + roomTypeIdStr);

        List<Room> rooms ;
        RoomService roomService = new RoomService();

        try {
            if (roomTypeIdStr != null && !roomTypeIdStr.trim().isEmpty()) {
                int roomTypeId = Integer.parseInt(roomTypeIdStr);
                System.out.println("通过roomTypeId查询房间: " + roomTypeId);
                rooms = roomService.getRoomsByRoomTypeId(roomTypeId);
            } else if (shopIdStr != null && !shopIdStr.trim().isEmpty()) {
                int shopId = Integer.parseInt(shopIdStr);
                System.out.println("通过shopId查询房间: " + shopId);
                rooms = roomService.getRoomsByShopId(shopId);
            } else {
                System.out.println("缺少必要参数，请提供shopId或roomTypeId");
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "缺少shopId或roomTypeId参数")));
                return;
            }

            // 只返回可用房间
            List<Room> availableRooms = new java.util.ArrayList<>();
            for (Room room : rooms) {
                if ("available".equals(room.getStatus())) {
                    availableRooms.add(room);
                }
            }

            System.out.println("返回的availableRooms: " + gson.toJson(availableRooms));
            System.out.println("查询结果: 总房间数=" + rooms.size() + ", 可用房间数=" + availableRooms.size());
            resp.getWriter().write(gson.toJson(Result.success(availableRooms)));

        } catch (NumberFormatException e) {
            System.out.println("参数格式错误: " + e.getMessage());
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "参数格式错误: " + e.getMessage())));
        } catch (Exception e) {
            System.out.println("获取可用房间失败: " + e.getMessage());
            e.printStackTrace();
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "获取可用房间失败: " + e.getMessage())));
        }
    }

    /**
     * 处理支付订单请求
     */

    private void handlePayOrder(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        System.out.println("[CustomerServlet.handlePayOrder] 收到支付请求，用户ID: " + customerUser.getId());

        // 读取 JSON 请求体
        BufferedReader reader = req.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        JsonObject jsonObject = gson.fromJson(jsonBuilder.toString(), JsonObject.class);

        // 获取订单ID
        String orderIdStr = jsonObject != null && jsonObject.has("orderId") ? jsonObject.get("orderId").getAsString() : null;
        if (orderIdStr == null || orderIdStr.trim().isEmpty()) {
            System.out.println("[CustomerServlet.handlePayOrder] 订单ID为空");
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "订单ID不能为空")));
            return;
        }

        try {
            int orderId = Integer.parseInt(orderIdStr);
            System.out.println("[CustomerServlet.handlePayOrder] 解析订单ID: " + orderId);

            // 调用控制器进行支付
            boolean success = clientController.payOrder(customerUser.getId(), orderId);
            if (success) {
                System.out.println("[CustomerServlet.handlePayOrder] 支付成功，订单ID: " + orderId);
                // 获取更新后的订单信息
                Order updatedOrder = orderService.getOrderById(orderId);
                resp.getWriter().write(gson.toJson(Result.success(updatedOrder, "支付成功")));
            } else {
                System.out.println("[CustomerServlet.handlePayOrder] 支付失败，订单ID: " + orderId);
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "支付失败")));
            }
        } catch (NumberFormatException e) {
            System.out.println("[CustomerServlet.handlePayOrder] 订单ID格式错误: " + e.getMessage());
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "订单ID格式不正确")));
        } catch (Exception e) {
            System.out.println("[CustomerServlet.handlePayOrder] 支付处理异常: " + e.getMessage());
            e.printStackTrace();
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "支付失败: " + e.getMessage())));
        }
    }

    /**
     * 处理获取签到统计数据请求
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleSignInStats(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        if (customerUser == null) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.UNAUTHORIZED, "用户未登录")));
            return;
        }

        Map<String, Object> stats = clientController.getSignInStats(customerUser.getId());
        resp.getWriter().write(gson.toJson(Result.success(stats)));
    }

    /**
     * 处理获取签到历史记录请求
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleSignInHistory(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        if (customerUser == null) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.UNAUTHORIZED, "用户未登录")));
            return;
        }

        List<SignInRecord> history = clientController.getSignInHistory(customerUser.getId());
        resp.getWriter().write(gson.toJson(Result.success(history)));
    }

    /**
     * 处理退房申请请求
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @param customerUser 当前登录的客户用户
     * @throws IOException IO异常
     */
    private void handleRefundRequest(HttpServletRequest req, HttpServletResponse resp, User customerUser) throws IOException {
        System.out.println("[CustomerServlet.handleRefundRequest] 开始处理退房申请");
        
        if (customerUser == null) {
            System.out.println("[CustomerServlet.handleRefundRequest] 用户未登录");
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.UNAUTHORIZED, "用户未登录")));
            return;
        }

        // 从请求体中读取JSON数据
        BufferedReader reader = req.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        JsonObject jsonObject = gson.fromJson(jsonBuilder.toString(), JsonObject.class);
        String orderIdStr = jsonObject != null && jsonObject.has("orderId") ? jsonObject.get("orderId").getAsString() : null;

        if (orderIdStr == null || orderIdStr.trim().isEmpty()) {
            System.out.println("[CustomerServlet.handleRefundRequest] 订单ID为空");
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "订单ID不能为空")));
            return;
        }

        try {
            Integer orderId = Integer.parseInt(orderIdStr);
            System.out.println("[CustomerServlet.handleRefundRequest] 解析订单ID: " + orderId);

            // 调用服务层处理退房申请
            boolean success = orderService.requestRefund(customerUser.getId(), orderId);
            
            if (success) {
                System.out.println("[CustomerServlet.handleRefundRequest] 退房申请提交成功");
                resp.getWriter().write(gson.toJson(Result.success("退房申请已提交，请等待商家审核")));
            } else {
                System.out.println("[CustomerServlet.handleRefundRequest] 退房申请提交失败");
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "退房申请提交失败")));
            }
        } catch (NumberFormatException e) {
            System.out.println("[CustomerServlet.handleRefundRequest] 订单ID格式错误: " + e.getMessage());
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "订单ID格式不正确")));
        } catch (Exception e) {
            System.out.println("[CustomerServlet.handleRefundRequest] 处理退房申请异常: " + e.getMessage());
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.INTERNAL_SERVER_ERROR, "退房申请失败: " + e.getMessage())));
        }
    }
}
